/**
排序
*/
package main

import (
	"fmt"
	"sort"
)

type SortObject struct {
	id   int
	name string
}

type SortObjects []SortObject

func (objs SortObjects) Len() int {
	return len(objs)
}

func (objs SortObjects) Less(i int, j int) bool {
	return objs[i].id < objs[j].id
}

func (objs SortObjects) Swap(i int, j int) {
	objs[i], objs[j] = objs[j], objs[i]
}

func main() {
	nums := []int{1, 5, 3}
	sort.Ints(nums)
	fmt.Println("nums:", nums)

	nums = []int{1, 5, 3, 2, 10, 2}
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] < nums[j]
	})
	fmt.Println("nums:", nums)

	objs := SortObjects{
		{
			id:   2,
			name: "222",
		}, {
			id:   1,
			name: "111",
		}, {
			id:   3,
			name: "333",
		},
	}

	// 内部用反射，有一定的性能损耗
	//sort.Slice(objs, func(i, j int) bool {
	//	return objs[i].id < objs[j].id
	//})

	// sort.Sort()得实现三个方法 Len\Less\Swap，还得为数组重新定义别名或者进行包装xxxWrapper
	sort.Sort(objs)

	fmt.Println("objs", objs)

	fmt.Println("=====字符串排序与逆序=====")
	strs := []string{"2", "1", "3"}
	sort.Sort(sort.StringSlice(strs))
	fmt.Println(strs)

	strs = []string{"2", "1", "3"}
	sort.Sort(sort.Reverse(sort.StringSlice(strs)))
	fmt.Println(strs)
}
